<template>
  <a-card :bordered="false">

    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="表单名称">
              <a-input v-model="queryParam.wsName" placeholder=""/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="所属应用">
              <a-cascader
                :options="options"
                :show-search="{ filter }"
                :value="queryParam.visualData || []"
                :display-render="displayRender"
                placeholder="请选择应用"
                @change="onCascaderChange"
                expand-trigger="hover"
              />
            </a-form-item>
          </a-col>
          <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" @click="queryWorksheetInfo">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetQueryParam">重置</a-button>
              </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!--新增按钮-->
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
    </div>

    <s-table
      ref="table"
      size="default"
      rowKey="id"
      :columns="columns"
      :data="loadData"
      :alert="true"
      :rowSelection="rowSelection"
      showPagination="auto"
    >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
      <!--<span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter"/>
        </span>
      <span slot="description" slot-scope="text">
          <ellipsis :length="4" tooltip>{{ text }}</ellipsis>
        </span>-->
      <span slot="visual" slot-scope="text">
          <ellipsis :length="20" tooltip v-if="text">{{ getVisualName(text) }}</ellipsis>
          <ellipsis :length="8" tooltip v-if="!text">DEFAULT</ellipsis>
      </span>

      <span slot="action" slot-scope="text, record">
          <template>
            <a-tooltip placement="top" title="记录">
             <a style="color: navy" @click="handleView(record)"><a-icon type="database" theme="twoTone" /></a>
            </a-tooltip>
            <template v-if="$appAuth(record)">
            <a-divider type="vertical"/>
              <a-tooltip placement="top" title="修改">
              <a @click="handleEdit(record)"><a-icon type="edit" theme="twoTone" /></a>
              </a-tooltip>
              <a-divider type="vertical"/>
              <a-tooltip placement="top" title="配置">
                <a style="color: blue" @click="handleConfig(record)"><a-icon type="setting" theme="twoTone" /></a>
              </a-tooltip>
              <a-divider type="vertical"/>
              <a-tooltip placement="top" title="删除">
                <a style="color: red" @click="handleDel(record)"><a-icon type="delete" /></a>
              </a-tooltip>
              <a-divider type="vertical"/>
              <a-tooltip placement="top" title="API">
                <a style="color: red" @click="handleAPI(record)"><a-icon type="api" theme="twoTone" /></a>
              </a-tooltip>
            </template>
          </template>
        </span>
    </s-table>

    <add-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      :mode="mode"
      :options="options"
      @cancel="handleCancel"
      @ok="handleOk"
    />

    <delete-modal
      ref="deleteModal"
      :visible="delVisible"
      :loading="confirmLoading"
      :model="deleteModel"
      @cancel="handleDelCancel"
      @ok="handleDelOk"
    />
  </a-card>
</template>

<script>
  import { STable, Ellipsis } from '@/components'
  import { getWorksheetInfo, deleteWorksheet, updateWorksheetName, getCascadeData } from '@/api/worksheet'

  import AddForm from '@/views/worksheet/modules/AddForm'
  import DeleteModal from '@/views/worksheet/modules/DeleteModal'

  import store from '@/store'

  const columns = [
    {
      title: '#',
      scopedSlots: { customRender: 'serial' }
    },
    {
      title: '表单名称',
      dataIndex: 'wsName',
      scopedSlots: { customRender: 'wsName' }
    },
    {
      title: '字段数',
      dataIndex: 'fields',
      customRender: (text) => text.length + ' 个'
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      sorter: true,
    },
    {
      title: '所属应用',
      dataIndex: 'visualData',
      scopedSlots: { customRender: "visual" }
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: '200px',
      scopedSlots: { customRender: 'action' }
    }
  ]

  export default {
    name: 'WorksheetView',
    components: {
      STable,
      Ellipsis,
      AddForm,
      DeleteModal
    },
    data () {
      this.columns = columns
      return {
        advanced: false,
        options: [], // 视图选择数据
        mode: 'Edit',
        visible: false,
        delVisible: false,
        confirmLoading: false,
        mdl: null,
        deleteModel: null,
        // 查询参数
        defaultQueryParam: {
          visualData: []
        },
        queryParam: {
          visualData: []
        },
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          const requestParameters = Object.assign({}, parameter, this.queryParam)
          // console.log('loadData request parameters:', requestParameters)
          return getWorksheetInfo(requestParameters)
            .then(res => {
              // console.log('表格数据', res)
              return res
            })
        },
        selectedRowKeys: [],
        selectedRows: []
      }
    },
    methods: {
      resetQueryParam () {
        this.queryParam = { ...this.defaultQueryParam }
        store.dispatch('SetWorksheetQueryParam', this.queryParam)
      },
      queryWorksheetInfo () {
        store.dispatch('SetWorksheetQueryParam', this.queryParam)
        this.$refs.table.refresh(true)
      },
      onCascaderChange (v) {
        // v 的长度可能为 1，2，3
        if (v.length !== 3 && v.length !== 0) { return }
        this.queryParam.visualData = v;
        this.queryParam.visualId = v[2];
      },
      filter (inputValue, path) {
        return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
      },
      displayRender ({ labels }) {
        return labels[labels.length - 1];
      },
      getVisualName (visualData) {
        if (!Array.isArray(visualData)) {
          return ''
        }
        let visualId = ''
        if (visualData.length === 2) {
          visualId = visualData[1]
        } else if (visualData.length === 3) {
          visualId = visualData[2]
        }
        // console.log(this.options, visualId)
        if (visualId === "") { return "" }
        const getLabel = function (arr) {
          for (let i = 0; i < arr.length; i++) {
            const value = arr[i]
            if (value.value === visualId) {
              return value.label
            }
            if (value.children) {
              const label = getLabel(value.children)
              if (label && label !== "") {
                return label
              }
            }
          }
        }
        const label = getLabel(this.options)
        // console.log(label)
        return label
      },
      getVisualData (visualId) {
        const visualData = []
        const getLabel = function (arr, depth) {
          for (let i = 0; i < arr.length; i++) {
            const value = arr[i]
            visualData[depth - 1] = value.value
            if (value.value === visualId) {
              return true
            }
            if (value.children) {
              return getLabel(value.children, depth + 1)
            }
          }
        }

        const find = getLabel(this.options, 1)
        return find ? visualData : []
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      handleView (record) {
        this.mdl = { ...record }
        this.$router.push({
          name: 'WorksheetRows',
          params: {
            id: this.mdl.id
          }
        })
      },
      handleEdit (record) {
        console.log('record', record)
        this.mode = 'Edit'
        this.visible = true
        this.mdl = { ...record }
      },
      doEditName (model) {
        this.confirmLoading = true
        console.log('修改名称', model)
        if (Array.isArray(model.visualData) && model.visualData.length === 0) {
          model.visualData = ''
        }
        updateWorksheetName(model).then(res => {
          this.confirmLoading = false
          if (res.code === 200) {
            this.$refs.table.refresh()
            this.$message.info(`修改成功`)
          } else {
            this.$message.error(`修改失败`)
          }
        })
      },
      handleConfig (record) {
        this.mdl = { ...record }
        this.$router.push({
          name: 'EditWorksheet',
          params: {
            mdl: this.mdl
          }
        })
      },
      handleDel (record) {
        console.log('recode', record)

        this.delVisible = true
        this.deleteModel = { ...record }
        this.deleteModel['name'] = record['wsName']
      },
      handleAdd () {
        this.mode = 'Add'
        this.mdl = null
        this.visible = true
        // this.$router.push({ path: '/EditWorksheet' })
      },
      handleAPI (record) {
        this.$router.push({
          name: 'WorksheetApi',
          params: {
            id: record.id,
            mdl: record,
          }
        })
        // window.open(routeOne.href, '_blank')
      },
      handleOk (param = {}) {
        const { source } = param
        const form = this.$refs.createModal.form
        this.confirmLoading = true
        form.validateFields((errors, values) => {
          if (!errors) {
            console.log('values', values)
            this.confirmLoading = false
            this.visible = false

            if (this.mode === 'Add') {
              if (source) {
                this.$refs.table.refresh()
              } else {
                this.$router.push({
                  name: 'EditWorksheet',
                  params: {
                    mdl: values
                  }
                })
              }
            } else if (this.mode === 'Edit') {
              this.doEditName(values)
            }
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleCancel () {
        this.visible = false

        const form = this.$refs.createModal.form
        form.resetFields() // 清理表单数据（可不做）
      },
      handleDelCancel () {
        this.delVisible = false
      },
      handleDelOk (record) {
        this.confirmLoading = true
        deleteWorksheet(record.id).then(res => {
          this.delVisible = false
          this.confirmLoading = false
          if (res.code === 200) {
            // 刷新表格
            this.$refs.table.refresh()
            this.$message.info(`${record.wsName} 删除成功`)
          } else {
            this.$message.error(`${record.wsName} 删除失败`)
          }
        })
      }
    },
    computed: {
      rowSelection () {
        return {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      }
    },
    created () {
      // const param = { visualType: 'ThreeD' }
      const param = store.state.worksheet.worksheetQueryParam
      const visualId = this.$route.params.visualId || ''
      if (visualId && !param.visualData) {
        Object.assign(this.queryParam, { visualId })
      }
      Object.assign(this.queryParam, param)
      getCascadeData().then(res => {
        if (res.code === 200) {
          this.options = res.data
          const visualData = this.getVisualData(visualId)
          if (visualData.length === 3 && !param.visualData) {
            Object.assign(this.queryParam, { visualData })
          }
        } else {
          this.$message.error(`获取分类失败`)
        }
      })
    }
  }
</script>

<style scoped>

</style>
